'use strict'

const Controller = require('egg').Controller

class BingController extends Controller {
  async index() {
    const bingHost = 'https://www.bing.com'
    const { ctx } = this
    const { idx, rand } = ctx.query

    const indexFromQuery = parseInt(idx)
    let index = 0

    if (rand === '1') {
      index = Math.floor(50 * Math.random())
    } else if (Number.isInteger(indexFromQuery) && indexFromQuery > 0) {
      index = indexFromQuery
    }

    try {
      const res = await ctx.curl(`${bingHost}/HPImageArchive.aspx?format=js&idx=${index}&n=1&mkt=en-US`, {
        method: 'GET',
        dataType: 'json',
      })

      if (res && res.data && Array.isArray(res.data.images) && res.data.images.length > 0) {
        const imageObj = res.data.images[0]
        ctx.body = { code: 2000, data: `${bingHost}${imageObj.url}`, msg: 'ok' }
      } else {
        ctx.body = { code: 5000, data: res.data, msg: '获取不到图片' }
      }
    } catch (err) {
      ctx.body = { code: 5000, data: null, msg: '获取不到图片' }
    }
  }
}

module.exports = BingController
